﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Media.Imaging;
using CommunitySystem.JinShengService;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows.Printing;
using System.Runtime.InteropServices.Automation;


namespace CommunitySystem.PageView
{
    public partial class ZKZYLWindow : ChildWindow
    {
        private JinShengServiceClient _client = new JinShengServiceClient();
        private int zkzID = -1;
       private ZKZEmpInfo _ZKZEmpInfo = null;
        public ZKZYLWindow(ZKZEmpInfo SelZKZEmpInfo)
        {
            InitializeComponent();
            
       
            zkzID = SelZKZEmpInfo.ID;


       

            client1 = new PublicOfficialSelectionService.PublicOfficialSelectionServiceClient();
            client1.ValidateHasPhotoCompleted += new EventHandler<PublicOfficialSelectionService.ValidateHasPhotoCompletedEventArgs>(client_ValidateHasPhotoCompleted);
            client1.UploadFileCompleted += new EventHandler<PublicOfficialSelectionService.UploadFileCompletedEventArgs>(client_UploadFileCompleted);
            client1.UpdateHasPotoCompleted += new EventHandler<PublicOfficialSelectionService.UpdateHasPotoCompletedEventArgs>(client_UpdateHasPotoCompleted);
            

            Load();
        }

        private void Load()
        {
            IsWorking.Visibility=Visibility.Visible;
            _client.GetZKZEmpInfoCompleted += (s, e) =>
            {

                this.DataContext = _ZKZEmpInfo = e.Result.First();

                var kssj = _ZKZEmpInfo.KSSJ.Split('/');
                for (int i = 0; i < kssj.Count(); i++)
                {
                    StackPanel sp = new StackPanel() { Orientation = Orientation.Horizontal };
                    TextBlock t1 = new TextBlock() { Text = kssj[i].Split(';')[0].ToString() };
                    TextBlock t2 = new TextBlock() { Margin = new Thickness(20, 0, 0, 0), Text = kssj[i].Split(';')[1].ToString() };
                    TextBlock t3 = new TextBlock() { Margin = new Thickness(100, 0, 0, 0), Text = kssj[i].Split(';')[2].ToString() };

                    sp.Children.Add(t1);
                    sp.Children.Add(t2);
                    sp.Children.Add(t3);

                    this.spkssj.Children.Add(sp);
                }

                if (!string.IsNullOrEmpty(_ZKZEmpInfo.PhotoName))
                {
                    _client.DownLoadPhotoAsync(_ZKZEmpInfo.PhotoName);
                    _client.DownLoadPhotoCompleted += (ss, ee) => {
                        if (ee.Result == null)
                        {
                            IsWorking.Visibility = Visibility.Collapsed;
                            return;
                        }
                        BitmapImage b = new BitmapImage();
                        Stream mm = new MemoryStream(ee.Result);
                        b.SetSource(mm);
                        imgPhoto.Source = b;
                        IsWorking.Visibility = Visibility.Collapsed;
                    };
                    #region
                    //ObservableCollection<byte> context = new ObservableCollection<byte>();
                    //CommunitySystem.PublicOfficialSelectionService.PublicOfficialSelectionServiceClient client = new PublicOfficialSelectionService.PublicOfficialSelectionServiceClient();
                    //client.DownLoadFileAsync(new PublicOfficialSelectionService.DownLoadFile() { Content = null, FileName = _ZKZEmpInfo.PhotoName, StartPosition = 0, Lenght = 1600, HasFinished = false, PathKey = "photo" });
                    //client.DownLoadFileCompleted += (sender1, e1) =>
                    //{
                    //    CommunitySystem.PublicOfficialSelectionService.DownLoadFile file = e1.Result;
                    //    if (file == null)
                    //    {
                    //        //SilverlightMessageBoxLibrary.Message.ErrorMessage(_ZKZEmpInfo.EmpName + "的图片错误，请联系管理员!");
                    //        IsWorking.Visibility = Visibility.Collapsed;
                    //        return;
                    //    }
                    //    foreach (byte b in file.Content)
                    //    {
                    //        context.Add(b);
                    //    }
                    //    if (file.HasFinished == true)
                    //    {
                    //        BitmapImage b = new BitmapImage();
                    //        Stream mm = new MemoryStream(context.ToArray<byte>());
                    //        b.SetSource(mm);
                    //        imgPhoto.Source = b;
                    //        IsWorking.Visibility = Visibility.Collapsed;
                    //    }
                    //    else
                    //    {
                    //        file.StartPosition += file.Lenght;
                    //        client.DownLoadFileAsync(file);
                    //    }
                    //};
                    #endregion
                }

            };
            _client.GetZKZEmpInfoAsync(string.Format(" and zkz.ID={0}",zkzID));

           
        }
   
        /// <summary>
        /// 打印
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            //this.DialogResult = true;
            PrintDocument document = new PrintDocument();



            // tell the API what to print
            document.PrintPage += (s, args) =>
            {
                args.PageVisual = spAll;
            };

            // call the Print() with a proper name which will be visible in the Print Queue
            document.Print("Silverlight Print Application Demo");


            //ElementToPNG eTP = new ElementToPNG();
            //eTP.ShowSaveDialog(spAll);

            //object missingValue = System.Reflection.Missing.Value;
            //dynamic wordApplication = AutomationFactory.CreateObject("Word.Application");
            //wordApplication.Visible = false;
            //dynamic doc = wordApplication.Documents.Add();
            //wordApplication.ActiveDocument.pagesetup.topmargin = 13.3; //设置word文档的上边距
            //wordApplication.ActiveDocument.pagesetup.bottommargin = 53.3;//设置word文档的下边距
            //wordApplication.ActiveDocument.pagesetup.leftmargin = 56.7;//设置word文档的左边距
            //wordApplication.ActiveDocument.pagesetup.rightmargin = 56.7;//设置word文档的右边距
            //dynamic rng = wordApplication.Range;
            //int start = doc.Characters.Count - 1; //定义文本的坐标
            //int end = doc.Characters.Count - 1;
            //rng = doc.content;
            //rng = doc.Range(ref start, ref end);
            //rng.Text = "文档标题" + "\r\n";
            //rng.font.size = 22;
            //rng.font.name = "黑体"; //设置字体
            //rng.ParagraphFormat.Alignment = 1; //设置水平居中
            //dynamic rng1 = wordApplication.Range;
            //int start1 = doc.Characters.Count - 1;
            //int end1 = doc.Characters.Count - 1;
            //rng1 = doc.content;
            //rng1 = doc.Range(ref start1, ref end1);
            //rng1.Text = "自办单位名称：" + "cccccccccc" + "" + "团组号：" + "";
            //rng1.font.size = 12;
            //rng1.font.name = "楷体_GB2312";
            //dynamic table;
            //int Tstart = doc.Characters.Count - 1;
            //int Tend = doc.Characters.Count - 1;
            //Object tableLocation = doc.Range(ref　Tstart, ref　Tend);
            //table = doc.Tables.Add(tableLocation, 5, 8, ref missingValue, ref missingValue); //在指定位置插入表格
            //table.Borders.OutsideLineStyle = 1; //显示表格的边框线
            //table.Borders.InsideLineStyle = 1;

            //table.cell(1, 1).Range.Text = "姓";
            //table.cell(1, 1).Range.font.size = 14;
            //table.cell(1, 1).Range.font.name = "楷体_GB2312";
            //table.cell(1, 1).width = 45.1f; //设置单元格的宽度
            //table.cell(1, 1).Range.ParagraphFormat.Alignment = 1; //设置单元格垂直的居中方式

            //table.cell(1, 2).width = 58.8f;
            //table.cell(1, 2).Range.Text = "tteettttttttttt";
            //table.cell(1, 2).Range.font.size = 14;
            //table.cell(1, 2).Range.font.name = "楷体_GB2312";
            //table.cell(1, 2).Range.ParagraphFormat.Alignment = 1;

            //table.cell(1, 3).Range.Text = "名";
            //table.cell(1, 3).Range.font.size = 14;
            //table.cell(1, 3).Range.font.name = "楷体_GB2312";
            //table.cell(1, 3).width = 45.1f;
            //table.cell(1, 3).Range.ParagraphFormat.Alignment = 1;

            //table.cell(1, 4).width = 90.3f;
            //table.cell(1, 4).Range.Text = "aaaaaaaaaaaaaaaaaaaaa";
            //table.cell(1, 4).Range.font.size = 14;
            //table.cell(1, 4).Range.font.name = "楷体_GB2312";
            //table.cell(1, 4).Range.ParagraphFormat.Alignment = 1;
            ////missingValue = ccccc(missingValue, wordApplication, doc);

            //_client.ExportZKZCompleted += new EventHandler<ExportZKZCompletedEventArgs>(_client_ExportZKZCompleted);
            //_client.ExportZKZAsync(missingValue, wordApplication, doc,"jinjin");
        }

        void _client_ExportZKZCompleted(object sender, ExportZKZCompletedEventArgs e)
        {
            if (e.Error == null)
                MessageBox.Show("导出成功");
        }

       

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        /// <summary>
        /// 验证那些人是否已经有照片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        ObservableCollection<CommunitySystem.PublicOfficialSelectionService.Emp_BasicInfoModel> allpeople = null;
        ObservableCollection<CommunitySystem.PublicOfficialSelectionService.Emp_BasicInfoModel> hasphoto = null;
        void client_ValidateHasPhotoCompleted(object sender, PublicOfficialSelectionService.ValidateHasPhotoCompletedEventArgs e)
        {
            allpeople = e.Result;
            var notin = fileNames.Where(c => allpeople.Where(d => d.CardNo.ToLower() == c.ToLower()).Count() <= 0);//from c in allpeople
            foreach (var r in allpeople)
            {
                var f = files.Where(c => c.Name.ToLower() == r.CardNo.ToLower()).FirstOrDefault();
                client1.UploadFileAsync("photo", f.DisplayName, f.Context[0], true, f);
                f.Context.RemoveAt(0);
                //UploadFileInfo f = files.Where(c => c.Name.ToLower() == r.CardNo.ToLower()).FirstOrDefault();
                //if (f != null)
                //{
                //    f.HasFinished = "/CommunitySystem;component/Images/ViewDesign/add.png";
                //    f.XingMin = r.Name;
                //}
            }
            //if (notin.Count() > 0)//有不卡号不匹配的情况
            //{
            //    string card = string.Empty;
            //    foreach (var p in notin)
            //    {
            //        card += p + "\n\t";
            //    }
            //    if (MessageBox.Show("以下图片名称不匹配数据库中人员卡号，是否导入已匹配图片?\n\t" + card, "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            //    {
            //        hasphoto = new ObservableCollection<PublicOfficialSelectionService.Emp_BasicInfoModel>(e.Result.Where(c => c.HasPhoto == true));
            //        if (hasphoto.Count() > 0)//有已经导入的
            //        {
            //            string hasphotoNames = string.Empty;
            //            foreach (var p in hasphoto)
            //            {
            //                if (hasphoto.IndexOf(p) == hasphoto.Count - 1)
            //                    hasphotoNames += p.Name + p.CardNo;
            //                else
            //                    hasphotoNames += p.Name + p.CardNo + "\n\t";
            //            }
            //            if (MessageBox.Show("以下人员图片已导入，是否覆盖?\n\t" + hasphotoNames, "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)//覆盖掉已导入的
            //            {
            //                foreach (var a in allpeople)
            //                {
            //                    var f = files.Where(c => c.Name.ToLower() == a.CardNo.ToLower()).FirstOrDefault();
            //                    client1.UploadFileAsync("photo", f.DisplayName, f.Context[0], true, f);
            //                    f.Context.RemoveAt(0);
            //                }
            //            }
            //            else//不覆盖
            //            {
            //                foreach (var a in allpeople)
            //                {
            //                    var f = files.Where(c => c.Name.ToLower() == a.CardNo.ToLower()).FirstOrDefault();
            //                    int count = hasphoto.Where(c => f.Name.ToLower() == c.CardNo.ToLower()).Count();
            //                    if (count <= 0)
            //                    {
            //                        client1.UploadFileAsync("photo", f.DisplayName, f.Context[0], true, f);
            //                        f.Context.RemoveAt(0);
            //                    }
            //                }
            //            }
            //        }
            //        else//没有已经导入的
            //        {
            //            foreach (var a in allpeople)
            //            {
            //                var f = files.Where(c => c.Name.ToLower() == a.CardNo.ToLower()).FirstOrDefault();
            //                if (f != null)
            //                {
            //                    client1.UploadFileAsync("photo", f.DisplayName, f.Context[0], true, f);
            //                    f.Context.RemoveAt(0);
            //                }
            //            }
            //        }

            //    }
            //}
            //else//没有卡号不匹配的
            //{
            //    hasphoto = new ObservableCollection<PublicOfficialSelectionService.Emp_BasicInfoModel>(e.Result.Where(c => c.HasPhoto == true));
            //    if (hasphoto.Count() > 0)//有已经导入的
            //    {
            //        string hasphotoNames = string.Empty;
            //        foreach (var p in hasphoto)
            //        {
            //            if (hasphoto.IndexOf(p) == hasphoto.Count - 1)
            //                hasphotoNames += p.Name + p.CardNo;
            //            hasphotoNames += p.Name + p.CardNo + "\n\t";
            //        }
            //        if (MessageBox.Show("以下人员图片已导入，是否覆盖?\n\t" + hasphotoNames, "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)//覆盖掉已导入的
            //        {
            //            foreach (var a in allpeople)
            //            {
            //                var f = files.Where(c => c.Name.ToLower() == a.CardNo.ToLower()).FirstOrDefault();
            //                client1.UploadFileAsync("photo", f.DisplayName, f.Context[0], true, f);
            //                f.Context.RemoveAt(0);
            //            }
            //        }
            //        else//不覆盖
            //        {
            //            foreach (var a in allpeople)
            //            {
            //                var f = files.Where(c => c.Name == a.CardNo).FirstOrDefault();
            //                int count = hasphoto.Where(c => f.Name.ToLower() == (c.CardNo.ToLower())).Count();
            //                if (count <= 0)
            //                {
            //                    client1.UploadFileAsync("photo", f.DisplayName, f.Context[0], true, f);
            //                    f.Context.RemoveAt(0);
            //                }
            //            }
            //        }
            //    }
            //    else//没有已经导入的
            //    {
            //        foreach (var a in allpeople)
            //        {
            //            var f = files.Where(c => c.Name.ToLower() == a.CardNo.ToLower()).FirstOrDefault();
            //            client1.UploadFileAsync("photo", f.DisplayName, f.Context[0], true, f);
            //            f.Context.RemoveAt(0);
            //        }
                 
            //    }
            //}
        }
        void client_UpdateHasPotoCompleted(object sender, PublicOfficialSelectionService.UpdateHasPotoCompletedEventArgs e)
        {
            UploadFileInfo f = e.UserState as UploadFileInfo;
            f.HasFinished = "/CommunitySystem;component/Images/ViewDesign/ok.png";
        }

        void client_UploadFileCompleted(object sender, PublicOfficialSelectionService.UploadFileCompletedEventArgs e)
        {
            UploadFileInfo f = e.UserState as UploadFileInfo;
            f.CurrentNo = f.parts - f.Context.Count;
            if (f.Context.Count > 0)
            {
                client1.UploadFileAsync("photo", f.DisplayName, f.Context[0], false, f);

                f.Context.RemoveAt(0);
            }
            else
            {
                
                client1.UpdateHasPotoAsync(f.Name, true, f.DisplayName, f);
            }
        }

        private List<string> fileNames = new List<string>();
        private ObservableCollection<UploadFileInfo> files = new ObservableCollection<UploadFileInfo>();
        private List<string> extendName = new List<string>()
        {
            "png",
            "jpg",
            "bmp"
        };
        private CommunitySystem.PublicOfficialSelectionService.PublicOfficialSelectionServiceClient client1 = null;
        public  OpenFileDialog openDlg = new OpenFileDialog();
        public FileStream fileStream;
        public byte[] m_imageBuffer;
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            files.Clear();
            //this.listBox1.ItemsSource = null; 
            #region  预览图片
            openDlg.Multiselect = false;
            openDlg.Filter = "图像文件(*.jpg;*.png;*.jpeg)|*.jpg;*.png;*.jpeg";
            bool? dlgResult = openDlg.ShowDialog();
            if (dlgResult == true)
            {
                if (openDlg.File != null)
                {
                    string[] fileName = openDlg.File.Name.Split('.');
                    if (fileName[0].ToString() != _ZKZEmpInfo.EmpCardNo)
                    {
                        MessageBox.Show("请将照片以身份证号命名！");
                        return;
                    }
                    if (!(fileName[fileName.Length - 1] == "jpg" || fileName[fileName.Length - 1] == "jpeg" || fileName[fileName.Length - 1] == "png"))
                    {
                        MessageBox.Show("请选择jpg、jpeg、png格式的文件！");
                        return;
                    }
                  
                    fileStream = openDlg.File.OpenRead();
                    UploadFileInfo info = new UploadFileInfo();
                    fileNames.Add(fileName[0]);
                    info.Name = fileName[0];
                    info.DisplayName = openDlg.File.Name;
                    Stream stream = openDlg.File.OpenRead();
                    int b = 0;
                    while (stream.Position > -1 && stream.Position < stream.Length)
                    {
                        if (stream.Length - fileStream.Position >= 16000)
                        {
                            b = 16000;
                        }
                        else
                        {
                            b = (int)(fileStream.Length - fileStream.Position);
                        }

                        byte[] filebyte = new byte[b];
                        stream.Read(filebyte, 0, b);
                        if (info.Context == null)
                            info.Context = new List<byte[]>();
                        info.Context.Add(filebyte);
                    }
                    info.parts = info.Context.Count;
                    files.Add(info);
                    /// <summary>  
                    /// 这段代码必须放在后面那段代码之前，否则m_imageBuffer存储的都是0，原因不明。  
                    /// </summary>  
                    long picLength = fileStream.Length;
                    m_imageBuffer = new byte[picLength];
                    fileStream.Read(m_imageBuffer, 0, (int)picLength);    // 读取图片 二进制 
                    BitmapImage bitmap = new BitmapImage();
                    bitmap.SetSource(fileStream);
                    this.imgPhoto.Source = bitmap;       //  预览图片

                   
                    ///获取图像的缓存存入字节数组m_imageBuffer中，方便以后保存头像  

                    fileStream.Close();

                }
                else
                {
                    MessageBox.Show("请选择图片！");
                }
            }
            //listBox1.ItemsSource = files;
            client1.ValidateHasPhotoAsync(new System.Collections.ObjectModel.ObservableCollection<string>(fileNames), EHR.Common.Session.LoginUser.LoginName);
      
          
            #endregion
        
          
        }


    }
}

